package sso.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import sso.util.JwtUtils;
import sso.util.WebUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.csrf().disable();
        http.formLogin()
                .successHandler(successHandler()) //登录成功
                .failureHandler(failureHandler());//登录失败
        http.exceptionHandling()
                .authenticationEntryPoint(entryPoint()); //提示要认证
        //所有资源都要认证
        http.authorizeRequests().anyRequest().authenticated();
    }

    private AuthenticationSuccessHandler successHandler(){
        return (request, respons, authentication) ->{
            Map<String , Object> map = new HashMap<>();
            map.put("state", 200);
            map.put("msg", "WDNMD，登录成功了");
            User user = (User) authentication.getPrincipal();

            List<String> auth = new ArrayList<>();
            user.getAuthorities().forEach((grantedAuthority -> {
                auth.add(grantedAuthority.getAuthority());
            }));

            Map<String ,Object> userInfo = new HashMap<>();
            userInfo.put("username", user.getUsername());
            userInfo.put("authentication", auth);

            System.out.println(auth);
            System.out.println(user.getAuthorities().toArray().toString());
            String token = JwtUtils.generateToken(userInfo);
            map.put("token", token);
            WebUtils.writeJson2Client(respons, map);
        };
    }

    private AuthenticationFailureHandler failureHandler(){
        return (request,response,exception)->{
            Map<String,Object> map=new HashMap<>();
            map.put("state",500);
            map.put("message","你妈的，输错了");
            WebUtils.writeJson2Client(response,map);
        };
    }

    private AuthenticationEntryPoint entryPoint(){
        return (request,response,exception)->{
            Map<String,Object> map=new HashMap<>();
            map.put("state",500);
            map.put("message","8041服务器，请先登录");
            WebUtils.writeJson2Client(response,map);
        };
    }
}
